<?php (defined('BASEPATH')) OR exit('No direct script access allowed');

class Model_auth extends MY_Model {
	
	var $table = "sys_users";
	
	function login($user,$pass){
		$this->load->database();
						
		  $sql = "SELECT sys_users.*,mst_pegawai.nama,sys_groups.name,mst_pegawai.pegawai_id reg FROM {$this->table}, mst_pegawai, sys_groups WHERE username='$user' AND sys_users.is_active='1' AND sys_users.pegawai_id = mst_pegawai.pegawai_id";
		$query = $this->db->query($sql);
		
		$this->db->close();
		
		foreach($query->result_array() as $row){
			if(sha1($pass) != $row['password'])
				return false;
		}
		
		return $this->create_session($query);
	}
	
	function logout(){
		$this->load->database();
		
		$id = $this->session->userdata('user_id');
		
		$data = array();
		$data['is_logged'] = 0;
		
		$this->db->where('user_id',$id);
		$this->db->update($this->table,$data);
		
		$this->db->close();
		
		$this->session->sess_destroy();
	}
	
	function get_user($id){
		$this->load->database();
						
		$sql = "SELECT * FROM {$this->table} WHERE user_id='$id' AND is_active='1'";
		$query = $this->db->query($sql);
		
		$this->db->close();
		
		return $query;
	}
	
	function switch_session(){
		$id = $this->session->userdata('user_id');
		
		$this->logout();
		
		$this->load->database();
						
		$sql = "UPDATE sys_users SET is_logged=0 WHERE user_id='$id'";
		$query = $this->db->query($sql);
		
		$this->db->close();
		
		$query = $this->get_user($id);
		
		$this->create_session($query);
	}
	
	function create_session($query){
		foreach($query->result() as $row){
			$diff = time() - strtotime($row->last_login);
			// if($row->is_logged == 1 && $diff < 3600){
				// $data = array(
					// 'switch'	=> TRUE,
					// 'user_id'	=> $row->user_id,
				// );
				// $this->session->set_userdata($data);
				
				// return false;
			// }else{
				
				// $this->load->helper('string');
				
				// $token = random_string('numeric', 50);

				$data = array(
					'login'		=> TRUE,
					'user_id'	=> $row->user_id,
					'nama'		=> $row->nama,
					'reg'		=> $row->reg,
					'username'	=> $row->username,
					'group'		=> $row->group_id,
					// 'token'		=> $token
				);
				$this->session->set_userdata($data);
				
				/*update table sys_users*/
				$data = array();
				$data['is_logged'] = 1;
				// $data['token'] = $token;
				$data['last_login'] = date("Y-m-d H:i:s");
				
				$this->db->where('user_id',$row->user_id);
				$this->db->update($this->table,$data);
				
				return true;
			// }
		}
	}

}

?>